/**
 * @Author       : cxh
 * @Date         : 2021-12-29 13:10:16
 * @LastEditTime : 2021-12-30 10:22:15
 * @LastEditors  : cxh
 * @Description  : user的增删查改实现
 * @FilePath     : \vue_WorkSpace\egg-wpt-server\app\controller\user.js
 */
'use strict';
const keyController = require('./../lib/keyController');
const Controller = require('egg').Controller;

class UserController extends Controller {
  async index() {
    const {
      ctx,
    } = this;
    // ctx.body = 'hi, user';
    ctx.body = await ctx.model.User.find();
  }
  async getUserList() {
    const {
      ctx,
    } = this;
    console.log('body:', ctx.request.body);
    // ctx.body = 'hi, user';
    ctx.body = await ctx.model.User.find();
  }
  async createUser() {
    const {
      ctx,
    } = this;
    // ctx.body = 'hi, user';
    ctx.body = await ctx.model.User.find();
  }

  // 注册新用户
  async registerAdmin() {
    const {
      ctx,
    } = this;
    const {
      body = {},
    } = ctx.request;
    const {
      name,
      password,
      phone,
      email,
      sex = 0,
      age = 0,
      lv,
    } = body;
    if (!name || !password || !phone || !email || ![ 0, 1, 2 ].includes(lv)) {
      ctx.body = {
        success: false,
        msg: 'name, password, phone, email,lv都是必传字段！',
        data: null,
      };
      return;
    }
    // 校验手机号唯一
    const findOneByPhone = await ctx.model.User.findOne({
      phone,
    });
    if (!findOneByPhone) {
      // 通过校验
      // 解密字段
      const real_pw = await keyController.decrypt(password);
      // 用户数据入库
      await ctx.model.User.create({
        name,
        phone,
        email,
        sex,
        age,
        lv,
        password: real_pw,
      });
      ctx.body = {
        success: true,
        msg: '注册成功',
        data: null,
      };
      return;

    }
  }

}

module.exports = UserController;
